const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));

// 添加根路径重定向到房间页面
app.get('/', (req, res) => {
  res.redirect('/rooms.html');
});

const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST']
  }
});

// 游戏房间管理
const rooms = {};

// 游戏配置
const GAME_CONFIG = {
  frameRate: 60,
  mapWidth: 1600,
  mapHeight: 1200,
  tankSpeed: 3,
  bulletSpeed: 5,
  maxPlayers: 8
};

// 创建新房间
function createRoom(roomName) {
  const roomId = uuidv4();
  // 生成唯一的房间名，使用时间戳和随机字符串组合
  const timestamp = new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
  const randomSuffix = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  const generatedRoomName = `坦克大战房间 ${timestamp}-${randomSuffix}`;
  
  // 确保房间名不重复
  const existingRoomNames = Object.values(rooms).map(room => room.name);
  let uniqueRoomName = generatedRoomName;
  let counter = 1;
  while (existingRoomNames.includes(uniqueRoomName)) {
    uniqueRoomName = `${generatedRoomName} (${counter})`;
    counter++;
  }
  
  rooms[roomId] = {
    id: roomId,
    name: uniqueRoomName,
    players: {},
    playerCount: 0,
    gameStarted: false,
    gameState: {
      tanks: {},
      bullets: {},
      walls: generateWalls(),
      timestamp: Date.now()
    },
    interval: null
  };
  return roomId;
}

// 生成墙壁
function generateWalls() {
  const walls = {};
  // 边界墙
  for (let i = 0; i < GAME_CONFIG.mapWidth; i += 20) {
    // 上边界
    const topWallId = uuidv4();
    walls[topWallId] = {
      id: topWallId,
      x: i,
      y: 0,
      width: 20,
      height: 20,
      health: 3,
      maxHealth: 3,
      isEdgeWall: true  // 边界墙不可摧毁
    };
    
    // 下边界
    const bottomWallId = uuidv4();
    walls[bottomWallId] = {
      id: bottomWallId,
      x: i,
      y: GAME_CONFIG.mapHeight - 20,
      width: 20,
      height: 20,
      health: 3,
      maxHealth: 3,
      isEdgeWall: true  // 边界墙不可摧毁
    };
  }
  
  for (let i = 0; i < GAME_CONFIG.mapHeight; i += 20) {
    // 左边界
    const leftWallId = uuidv4();
    walls[leftWallId] = {
      id: leftWallId,
      x: 0,
      y: i,
      width: 20,
      height: 20,
      health: 3,
      maxHealth: 3,
      isEdgeWall: true  // 边界墙不可摧毁
    };
    
    // 右边界
    const rightWallId = uuidv4();
    walls[rightWallId] = {
      id: rightWallId,
      x: GAME_CONFIG.mapWidth - 20,
      y: i,
      width: 20,
      height: 20,
      health: 3,
      maxHealth: 3,
      isEdgeWall: true  // 边界墙不可摧毁
    };
  }
  
  // 添加一些随机的内部墙壁（数量增加一倍）
  for (let i = 0; i < 80; i++) {
    const wallId = uuidv4();
    const x = Math.floor(Math.random() * (GAME_CONFIG.mapWidth - 100) / 20) * 20 + 40;
    const y = Math.floor(Math.random() * (GAME_CONFIG.mapHeight - 100) / 20) * 20 + 40;
    const width = Math.floor(Math.random() * 3 + 1) * 20;
    const height = Math.floor(Math.random() * 3 + 1) * 20;
    
    walls[wallId] = {
      id: wallId,
      x,
      y,
      width,
      height,
      health: 3,
      maxHealth: 3,
      isEdgeWall: false  // 内部墙壁可以被摧毁
    };
  }
  
  return walls;
}

// 开始游戏循环
function startGameLoop(roomId) {
  const room = rooms[roomId];
  if (!room) return;
  
  room.gameStarted = true;
  
  // 设置玩家初始位置
  const spawnPositions = [
    { x: 60, y: 60 },
    { x: GAME_CONFIG.mapWidth - 80, y: 60 },
    { x: 60, y: GAME_CONFIG.mapHeight - 80 },
    { x: GAME_CONFIG.mapWidth - 80, y: GAME_CONFIG.mapHeight - 80 },
    // 增加4个新的出生点以支持8名玩家
    { x: GAME_CONFIG.mapWidth / 2, y: 60 },
    { x: GAME_CONFIG.mapWidth / 2, y: GAME_CONFIG.mapHeight - 80 },
    { x: 60, y: GAME_CONFIG.mapHeight / 2 },
    { x: GAME_CONFIG.mapWidth - 80, y: GAME_CONFIG.mapHeight / 2 }
  ];
  
  let posIndex = 0;
  for (const playerId in room.players) {
    const player = room.players[playerId];
    
    // 检查玩家是否已经有坦克（断线重连的情况）
    let playerHasTank = false;
    for (const tankId in room.gameState.tanks) {
      const tank = room.gameState.tanks[tankId];
      if (tank.playerId === playerId) {
        playerHasTank = true;
        player.tankId = tankId;
        break;
      }
    }
    
    // 如果玩家没有坦克，才创建新坦克
    if (!playerHasTank) {
      let validPosition = false;
      let pos;
      let attempts = 0;
      const maxAttempts = spawnPositions.length * 2; // 最大尝试次数
      
      while (!validPosition && attempts < maxAttempts) {
        pos = spawnPositions[posIndex % spawnPositions.length];
        validPosition = true;
        
        // 检查与墙壁的碰撞
        for (const wallId in room.gameState.walls) {
          const wall = room.gameState.walls[wallId];
          if (checkCollision(
            { x: pos.x, y: pos.y, width: 40, height: 40 },
            wall
          )) {
            validPosition = false;
            break;
          }
        }
        
        // 检查与其他坦克的碰撞
        if (validPosition) {
          for (const tankId in room.gameState.tanks) {
            const otherTank = room.gameState.tanks[tankId];
            if (checkCollision(
              { x: pos.x, y: pos.y, width: 40, height: 40 },
              otherTank
            )) {
              validPosition = false;
              break;
            }
          }
        }
        
        if (!validPosition) {
          posIndex++;
          attempts++;
        }
      }
      
      // 只有在找到有效位置时才创建坦克
      if (validPosition) {
        const tankId = uuidv4();
        room.gameState.tanks[tankId] = {
          id: tankId,
          playerId,
          x: pos.x,
          y: pos.y,
          width: 40,
          height: 40,
          direction: 'up',
          speed: GAME_CONFIG.tankSpeed,
          health: 100,
          color: player.color
        };
        
        player.tankId = tankId;
        posIndex++;
      } else {
        // 如果无法找到有效位置，尝试使用随机位置并增加检测范围
        let randomValidPosition = false;
        let randomX, randomY;
        let randomAttempts = 0;
        const maxRandomAttempts = 20; // 最大随机尝试次数
        
        while (!randomValidPosition && randomAttempts < maxRandomAttempts) {
          randomX = Math.floor(Math.random() * (GAME_CONFIG.mapWidth - 100)) + 50;
          randomY = Math.floor(Math.random() * (GAME_CONFIG.mapHeight - 100)) + 50;
          randomValidPosition = true;
          
          // 检查随机位置与墙壁的碰撞
          for (const wallId in room.gameState.walls) {
            const wall = room.gameState.walls[wallId];
            if (checkCollision(
              { x: randomX, y: randomY, width: 40, height: 40 },
              wall
            )) {
              randomValidPosition = false;
              break;
            }
          }
          
          // 检查随机位置与其他坦克的碰撞
          if (randomValidPosition) {
            for (const tankId in room.gameState.tanks) {
              const otherTank = room.gameState.tanks[tankId];
              if (checkCollision(
                { x: randomX, y: randomY, width: 40, height: 40 },
                otherTank
              )) {
                randomValidPosition = false;
                break;
              }
            }
          }
          
          randomAttempts++;
        }
        
        // 只有在找到有效的随机位置时才创建坦克
        if (randomValidPosition) {
          const tankId = uuidv4();
          room.gameState.tanks[tankId] = {
            id: tankId,
            playerId,
            x: randomX,
            y: randomY,
            width: 40,
            height: 40,
            direction: 'up',
            speed: GAME_CONFIG.tankSpeed,
            health: 100,
            color: player.color
          };
          
          player.tankId = tankId;
          console.log(`为玩家 ${playerId} 创建了坦克，使用随机位置(${randomX}, ${randomY})`);
        } else {
          console.log(`警告：无法为玩家 ${playerId} 找到有效的坦克生成位置`);
        }
      }
    }
    }
  
  // 游戏配置 - 分离逻辑帧率和网络帧率
  const LOGIC_FRAME_RATE = GAME_CONFIG.frameRate; // 60fps的逻辑更新
  const NETWORK_FRAME_RATE = 15; // 15fps的网络广播
  
  // 游戏逻辑更新循环
  room.logicInterval = setInterval(() => {
    updateGameState(roomId);
  }, 1000 / LOGIC_FRAME_RATE);
  
  // 网络状态广播循环
  room.networkInterval = setInterval(() => {
    // 添加时间戳，客户端可以用于插值
    room.gameState.timestamp = Date.now();
    io.to(roomId).emit('gameState', room.gameState);
  }, 1000 / NETWORK_FRAME_RATE);
}

// 更新游戏状态
function updateGameState(roomId) {
  const room = rooms[roomId];
  if (!room || !room.gameStarted) return;
  
  const { tanks, bullets, walls } = room.gameState;
  
  // 更新坦克位置
  for (const tankId in tanks) {
    const tank = tanks[tankId];
    
    // 跳过已断线的坦克，保持其状态不变
    if (tank.disconnected) {
      // 可以在这里添加断线超时清理逻辑，例如断线超过5分钟则移除坦克
      const disconnectDuration = Date.now() - tank.disconnectTime;
      if (disconnectDuration > 5 * 60 * 1000) { // 5分钟超时
        delete tanks[tankId];
        if (room.disconnectedPlayers) {
          // 查找并移除对应的断线玩家记录
          for (const playerId in room.disconnectedPlayers) {
            if (room.disconnectedPlayers[playerId].tankId === tankId) {
              delete room.disconnectedPlayers[playerId];
              break;
            }
          }
        }
      }
      continue;
    }
    
    const player = room.players[tank.playerId];
    
    if (player && player.input) {
      const { up, down, left, right, shoot } = player.input;
      
      // 处理移动
      let newX = tank.x;
      let newY = tank.y;
      
      if (up) {
        tank.direction = 'up';
        newY -= tank.speed;
      } else if (down) {
        tank.direction = 'down';
        newY += tank.speed;
      } else if (left) {
        tank.direction = 'left';
        newX -= tank.speed;
      } else if (right) {
        tank.direction = 'right';
        newX += tank.speed;
      }
      
      // 检测碰撞
      let collision = false;
      
      // 检查与墙壁的碰撞
      for (const wallId in walls) {
        const wall = walls[wallId];
        if (checkCollision(
          { x: newX, y: newY, width: tank.width, height: tank.height },
          wall
        )) {
          collision = true;
          break;
        }
      }
      
      // 检查与其他坦克的碰撞
      for (const otherTankId in tanks) {
        if (otherTankId !== tankId) {
          const otherTank = tanks[otherTankId];
          if (checkCollision(
            { x: newX, y: newY, width: tank.width, height: tank.height },
            otherTank
          )) {
            collision = true;
            break;
          }
        }
      }
      
      // 如果没有碰撞，更新位置
      if (!collision) {
        tank.x = newX;
        tank.y = newY;
      }
      
      // 处理射击
      if (shoot && !player.lastShootTime || (Date.now() - player.lastShootTime > 500)) {
        player.lastShootTime = Date.now();
        
        const bulletId = uuidv4();
        let bulletX = tank.x + tank.width / 2 - 5;
        let bulletY = tank.y + tank.height / 2 - 5;
        let velocityX = 0;
        let velocityY = 0;
        
        switch (tank.direction) {
          case 'up':
            bulletY = tank.y - 10;
            velocityY = -GAME_CONFIG.bulletSpeed;
            break;
          case 'down':
            bulletY = tank.y + tank.height;
            velocityY = GAME_CONFIG.bulletSpeed;
            break;
          case 'left':
            bulletX = tank.x - 10;
            velocityX = -GAME_CONFIG.bulletSpeed;
            break;
          case 'right':
            bulletX = tank.x + tank.width;
            velocityX = GAME_CONFIG.bulletSpeed;
            break;
        }
        
        bullets[bulletId] = {
          id: bulletId,
          tankId,
          playerId: tank.playerId,
          x: bulletX,
          y: bulletY,
          width: 10,
          height: 10,
          velocityX,
          velocityY
        };
      }
    }
  }
  
  // 更新子弹位置并检测碰撞
  const bulletsToRemove = [];
  const tanksToUpdate = {};
  
  for (const bulletId in bullets) {
    const bullet = bullets[bulletId];
    
    // 更新子弹位置
    bullet.x += bullet.velocityX;
    bullet.y += bullet.velocityY;
    
    // 检查子弹是否超出地图边界
    if (
      bullet.x < 0 ||
      bullet.x > GAME_CONFIG.mapWidth ||
      bullet.y < 0 ||
      bullet.y > GAME_CONFIG.mapHeight
    ) {
      bulletsToRemove.push(bulletId);
      continue;
    }
    
    // 检查子弹与墙壁的碰撞
    let wallCollision = false;
    for (const wallId in walls) {
      const wall = walls[wallId];
      if (checkCollision(bullet, wall)) {
        bulletsToRemove.push(bulletId);
        wallCollision = true;

        // 对墙壁造成伤害
        if (!wall.isEdgeWall) {
          wall.health = Math.max(0, wall.health - 1);
          if (wall.health <= 0) {
            delete walls[wallId];
          }
        }
        break;
      }
    }
    
    if (wallCollision) continue;
    
    // 检查子弹与其他子弹的碰撞
    let bulletCollision = false;
    for (const otherBulletId in bullets) {
      // 跳过自己
      if (otherBulletId === bulletId) continue;
      
      const otherBullet = bullets[otherBulletId];
      // 跳过已经标记为要移除的子弹
      if (bulletsToRemove.includes(otherBulletId)) continue;
      
      if (checkCollision(bullet, otherBullet)) {
        // 两颗子弹都被销毁
        bulletsToRemove.push(bulletId);
        bulletsToRemove.push(otherBulletId);
        bulletCollision = true;
        break;
      }
    }
    
    if (bulletCollision) continue;
    
    // 检查子弹与坦克的碰撞
    for (const tankId in tanks) {
      const tank = tanks[tankId];
      
      // 子弹不能打中发射它的坦克
      if (tank.id === bullet.tankId) continue;
      
      if (checkCollision(bullet, tank)) {
        bulletsToRemove.push(bulletId);
        
        // 减少坦克生命值
        tank.health -= 25;
        tanksToUpdate[tankId] = tank;
        
        // 如果坦克生命值为0，移除坦克
        if (tank.health <= 0) {
          delete tanks[tankId];
          
          // 从断线玩家列表中移除该玩家，这样重新加入时会被当作新玩家
          if (room.disconnectedPlayers) {
            for (const playerId in room.disconnectedPlayers) {
              if (room.disconnectedPlayers[playerId].tankId === tankId) {
                delete room.disconnectedPlayers[playerId];
                break;
              }
            }
          }
          
          // 通知玩家被击败
          io.to(tank.playerId).emit('defeated');
          
          // 检查游戏是否结束 - 需要考虑活跃玩家的坦克数量，而不是所有坦克
          // 统计每个玩家的活跃坦克数量
          const activePlayers = new Set();
          const disconnectedPlayers = new Set();
          
          // 收集所有活跃玩家和断线玩家
          for (const tankId in tanks) {
            const tank = tanks[tankId];
            if (tank.disconnected) {
              disconnectedPlayers.add(tank.playerId);
            } else {
              activePlayers.add(tank.playerId);
            }
          }
          
          // 只有当活跃玩家只剩下一个，且没有断线玩家时才宣布游戏结束
          // 这确保了即使所有玩家都断线，游戏也不会结束
          if (activePlayers.size === 1 && disconnectedPlayers.size === 0) {
            // 游戏结束，宣布胜利者
            const winnerPlayerId = Array.from(activePlayers)[0];
            let winnerTankId = null;
            
            // 找到胜利者的坦克ID
            for (const tankId in tanks) {
              if (tanks[tankId].playerId === winnerPlayerId) {
                winnerTankId = tankId;
                break;
              }
            }
            
            // 通知所有玩家游戏结束
            io.to(roomId).emit('gameOver', { winnerId: winnerPlayerId });
            
            room.gameStarted = false;
            
            // 清理游戏循环定时器
            if (room.logicInterval) {
              clearInterval(room.logicInterval);
              room.logicInterval = null;
            }
            if (room.networkInterval) {
              clearInterval(room.networkInterval);
              room.networkInterval = null;
            }
            
            // 清理所有玩家状态
            for (const playerId in room.players) {
              delete room.players[playerId];
              room.playerCount--;
            }
            
            // 清理断线玩家状态
            room.disconnectedPlayers = {};
            
            // 如果房间内没有活跃玩家，立即删除房间
            if (room.playerCount <= 0) {
              delete rooms[roomId];
              console.log(`游戏结束，房间 ${roomId} 已删除`);
            }
          }
        }
        
        break;
      }
    }
  }
  
  // 移除标记的子弹
  bulletsToRemove.forEach(bulletId => {
    delete bullets[bulletId];
  });
  
  // 更新时间戳
  room.gameState.timestamp = Date.now();
}

// 碰撞检测函数
function checkCollision(obj1, obj2) {
  return (
    obj1.x < obj2.x + obj2.width &&
    obj1.x + obj1.width > obj2.x &&
    obj1.y < obj2.y + obj2.height &&
    obj1.y + obj1.height > obj2.y
  );
}

// Socket.io 连接处理
io.on('connection', (socket) => {
  console.log('用户已连接:', socket.id);
  
  // 获取房间列表
  socket.on('getRooms', () => {
    const roomList = Object.values(rooms).map(room => ({
      id: room.id,
      name: room.name,
      playerCount: room.playerCount,
      gameStarted: room.gameStarted
    }));
    socket.emit('roomList', roomList);
  });
  
  // 创建房间
  socket.on('createRoom', ({ playerName, color }) => {
    const roomId = createRoom();
    socket.emit('roomCreated', { roomId });
  });
  
  // 加入房间
  socket.on('joinRoom', ({ roomId, playerName, persistentId }) => {
    const room = rooms[roomId];
    
    if (!room) {
      socket.emit('error', { message: '房间不存在' });
      return;
    }
    
    // 检查是否是断线重连的玩家
    let isReconnecting = false;
    let disconnectedPlayer = null;
    let disconnectedPlayerId = null;
    
    // 通过持久化ID来识别断线重连的玩家
    if (room.disconnectedPlayers && persistentId) {
      for (const playerId in room.disconnectedPlayers) {
        const player = room.disconnectedPlayers[playerId];
        // 使用持久化ID匹配断线玩家，而不是通过名称和颜色
        if (player.persistentId === persistentId && player.tankState && player.tankState.health > 0) {
          disconnectedPlayer = player;
          disconnectedPlayerId = playerId;
          isReconnecting = true;
          console.log(`玩家 ${playerName} (原ID: ${playerId}, 新ID: ${socket.id}, 持久ID: ${persistentId}) 正在重新连接`);
          break;
        }
      }
    }
    
    // 游戏已经开始但不是断线重连的玩家，仍然允许加入
    // 只检查房间是否已满
    // if (room.gameStarted && !isReconnecting) {
    //   socket.emit('error', { message: '游戏已经开始' });
    //   return;
    // }
    
    if (room.playerCount >= GAME_CONFIG.maxPlayers && !isReconnecting) {
      socket.emit('error', { message: '房间已满' });
      return;
    }
    
    // 将玩家加入房间
    socket.join(roomId);
    
    let playerColor;
    
    // 如果是断线重连的玩家，恢复其颜色和名称
    if (isReconnecting) {
      playerColor = disconnectedPlayer.color;
      playerName = disconnectedPlayer.name || playerName;
    } else {
      // 预定义8种不同的颜色
      const tankColors = [
        '#FF5252', // 红色
        '#4CAF50', // 绿色
        '#2196F3', // 蓝色
        '#FFC107', // 黄色
        '#9C27B0', // 紫色
        '#00BCD4', // 青色
        '#FF9800', // 橙色
        '#795548'  // 棕色
      ];
      
      // 查找当前房间已使用的颜色
      const usedColors = Object.values(room.players).map(player => player.color);
      
      // 从可用颜色中选择一个未使用的颜色
      for (const color of tankColors) {
        if (!usedColors.includes(color)) {
          playerColor = color;
          break;
        }
      }
      
      // 如果所有颜色都被使用了（理论上不会发生，因为最多8个玩家和8种颜色），随机生成一个颜色
      if (!playerColor) {
        playerColor = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
      }
    }
    
    // 添加玩家到房间
    room.players[socket.id] = {
      id: socket.id,
      name: playerName || `玩家 ${room.playerCount + 1}`,
      color: playerColor,
      input: {},
      lastShootTime: 0,
      persistentId: persistentId // 保存持久化ID
    };
    
    // 如果是断线重连的玩家，恢复其坦克状态
    if (isReconnecting && room.gameStarted) {
      const tankId = disconnectedPlayer.tankId;
      const tankState = disconnectedPlayer.tankState;
      
      if (tankId && tankState) {
        // 检查恢复位置是否有碰撞
        let validPosition = true;
        
        // 检查与墙壁的碰撞
        for (const wallId in room.gameState.walls) {
          const wall = room.gameState.walls[wallId];
          if (checkCollision(
            { x: tankState.x, y: tankState.y, width: 40, height: 40 },
            wall
          )) {
            validPosition = false;
            break;
          }
        }
        
        // 检查与其他坦克的碰撞
        if (validPosition) {
          for (const otherTankId in room.gameState.tanks) {
            // 跳过自己的坦克ID
            if (otherTankId === tankId) continue;
            
            const otherTank = room.gameState.tanks[otherTankId];
            if (checkCollision(
              { x: tankState.x, y: tankState.y, width: 40, height: 40 },
              otherTank
            )) {
              validPosition = false;
              break;
            }
          }
        }
        
        if (validPosition) {
          // 如果坦克已经被移除（例如被击毁），则重新创建坦克
          if (!room.gameState.tanks[tankId]) {
            room.gameState.tanks[tankId] = { ...tankState };
          }
          
          // 恢复坦克的完整状态，包括位置、方向、血量等
          room.gameState.tanks[tankId].playerId = socket.id;
          room.gameState.tanks[tankId].disconnected = false;
          room.gameState.tanks[tankId].x = tankState.x;
          room.gameState.tanks[tankId].y = tankState.y;
          room.gameState.tanks[tankId].direction = tankState.direction;
          room.gameState.tanks[tankId].health = tankState.health;
          delete room.gameState.tanks[tankId].disconnectTime;
          
          // 保存坦克ID到玩家对象
          room.players[socket.id].tankId = tankId;
          
          console.log(`已恢复玩家 ${socket.id} 的坦克状态，位置(${tankState.x}, ${tankState.y})，方向${tankState.direction}，血量${tankState.health}`);
        } else {
          // 如果原位置有碰撞，尝试找一个新的有效位置
          let newValidPosition = false;
          let newX, newY;
          let attempts = 0;
          const maxAttempts = 20;
          
          while (!newValidPosition && attempts < maxAttempts) {
            newX = Math.floor(Math.random() * (GAME_CONFIG.mapWidth - 100)) + 50;
            newY = Math.floor(Math.random() * (GAME_CONFIG.mapHeight - 100)) + 50;
            newValidPosition = true;
            
            // 检查新位置与墙壁的碰撞
            for (const wallId in room.gameState.walls) {
              const wall = room.gameState.walls[wallId];
              if (checkCollision(
                { x: newX, y: newY, width: 40, height: 40 },
                wall
              )) {
                newValidPosition = false;
                break;
              }
            }
            
            // 检查新位置与其他坦克的碰撞
            if (newValidPosition) {
              for (const otherTankId in room.gameState.tanks) {
                if (otherTankId === tankId) continue;
                
                const otherTank = room.gameState.tanks[otherTankId];
                if (checkCollision(
                  { x: newX, y: newY, width: 40, height: 40 },
                  otherTank
                )) {
                  newValidPosition = false;
                  break;
                }
              }
            }
            
            attempts++;
          }
          
          if (newValidPosition) {
            // 如果坦克已经被移除（例如被击毁），则重新创建坦克
            if (!room.gameState.tanks[tankId]) {
              room.gameState.tanks[tankId] = { ...tankState };
            }
            
            // 使用新位置恢复坦克状态
            room.gameState.tanks[tankId].playerId = socket.id;
            room.gameState.tanks[tankId].disconnected = false;
            room.gameState.tanks[tankId].x = newX;
            room.gameState.tanks[tankId].y = newY;
            room.gameState.tanks[tankId].direction = tankState.direction;
            room.gameState.tanks[tankId].health = tankState.health;
            delete room.gameState.tanks[tankId].disconnectTime;
            
            // 保存坦克ID到玩家对象
            room.players[socket.id].tankId = tankId;
            
            console.log(`已恢复玩家 ${socket.id} 的坦克状态，原位置有碰撞，使用新位置(${newX}, ${newY})，方向${tankState.direction}，血量${tankState.health}`);
          } else {
            console.log(`警告：无法为重连玩家 ${socket.id} 找到有效的坦克生成位置`);
          }
        }
      }
      
      // 从断线玩家列表中移除
      delete room.disconnectedPlayers[disconnectedPlayerId];
      
      // 重连的玩家也需要增加玩家计数，因为在断线时已经减少了计数
      room.playerCount++;

    } else {
      // 如果不是断线重连，增加玩家计数
      room.playerCount++;
      
      // 如果游戏已经开始，为新加入的玩家创建坦克
      if (room.gameStarted) {
        // 设置玩家初始位置
        const spawnPositions = [
          { x: 60, y: 60 },
          { x: GAME_CONFIG.mapWidth - 80, y: 60 },
          { x: 60, y: GAME_CONFIG.mapHeight - 80 },
          { x: GAME_CONFIG.mapWidth - 80, y: GAME_CONFIG.mapHeight - 80 }
        ];
        
        // 尝试找到一个无碰撞的生成位置
        let validPosition = false;
        let pos;
        let attempts = 0;
        const maxAttempts = spawnPositions.length * 2; // 最大尝试次数
        
        let posIndex = Math.floor(Math.random() * spawnPositions.length);
        
        while (!validPosition && attempts < maxAttempts) {
          pos = spawnPositions[posIndex % spawnPositions.length];
          validPosition = true;
          
          // 检查与墙壁的碰撞
          for (const wallId in room.gameState.walls) {
            const wall = room.gameState.walls[wallId];
            if (checkCollision(
              { x: pos.x, y: pos.y, width: 40, height: 40 },
              wall
            )) {
              validPosition = false;
              break;
            }
          }
          
          // 检查与其他坦克的碰撞
          if (validPosition) {
            for (const tankId in room.gameState.tanks) {
              const otherTank = room.gameState.tanks[tankId];
              if (checkCollision(
                { x: pos.x, y: pos.y, width: 40, height: 40 },
                otherTank
              )) {
                validPosition = false;
                break;
              }
            }
          }
          
          if (!validPosition) {
            posIndex++;
            attempts++;
          }
        }
        
        // 只有在找到有效位置时才创建坦克
        if (validPosition) {
          const tankId = uuidv4();
          room.gameState.tanks[tankId] = {
            id: tankId,
            playerId: socket.id,
            x: pos.x,
            y: pos.y,
            width: 40,
            height: 40,
            direction: 'up',
            speed: GAME_CONFIG.tankSpeed,
            health: 100,
            color: playerColor
          };
          
          // 保存坦克ID到玩家对象
          room.players[socket.id].tankId = tankId;
          console.log(`为游戏中加入的新玩家 ${socket.id} 创建了坦克，位置(${pos.x}, ${pos.y})`);
        } else {
          // 如果无法找到有效位置，尝试使用随机位置并增加检测范围
          let randomValidPosition = false;
          let randomX, randomY;
          let randomAttempts = 0;
          const maxRandomAttempts = 20; // 最大随机尝试次数
          
          while (!randomValidPosition && randomAttempts < maxRandomAttempts) {
            randomX = Math.floor(Math.random() * (GAME_CONFIG.mapWidth - 100)) + 50;
            randomY = Math.floor(Math.random() * (GAME_CONFIG.mapHeight - 100)) + 50;
            randomValidPosition = true;
            
            // 检查随机位置与墙壁的碰撞
            for (const wallId in room.gameState.walls) {
              const wall = room.gameState.walls[wallId];
              if (checkCollision(
                { x: randomX, y: randomY, width: 40, height: 40 },
                wall
              )) {
                randomValidPosition = false;
                break;
              }
            }
            
            // 检查随机位置与其他坦克的碰撞
            if (randomValidPosition) {
              for (const tankId in room.gameState.tanks) {
                const otherTank = room.gameState.tanks[tankId];
                if (checkCollision(
                  { x: randomX, y: randomY, width: 40, height: 40 },
                  otherTank
                )) {
                  randomValidPosition = false;
                  break;
                }
              }
            }
            
            randomAttempts++;
          }
          
          // 只有在找到有效的随机位置时才创建坦克
          if (randomValidPosition) {
            const tankId = uuidv4();
            room.gameState.tanks[tankId] = {
              id: tankId,
              playerId: socket.id,
              x: randomX,
              y: randomY,
              width: 40,
              height: 40,
              direction: 'up',
              speed: GAME_CONFIG.tankSpeed,
              health: 100,
              color: playerColor
            };
            
            // 保存坦克ID到玩家对象
            room.players[socket.id].tankId = tankId;
            console.log(`为游戏中加入的新玩家 ${socket.id} 创建了坦克，使用随机位置(${randomX}, ${randomY})`);
          } else {
            console.log(`警告：无法为游戏中加入的新玩家 ${socket.id} 找到有效的坦克生成位置`);
          }
        }
      }
    }
    
    // 通知玩家成功加入房间
    socket.emit('joinedRoom', {
      roomId,
      playerName: room.players[socket.id].name,
      color: room.players[socket.id].color
    });
    
    // 通知房间内所有玩家有新玩家加入
    io.to(roomId).emit('playerJoined', {
      playerId: socket.id,
      playerName: room.players[socket.id].name,
      playerCount: room.playerCount
    });
    
    // 如果游戏已经开始，通知新加入的玩家或重连的玩家
    if (room.gameStarted) {
      socket.emit('gameStarted');
    }
    // 如果房间内有足够的玩家且游戏未开始，开始游戏
    else if (room.playerCount >= 2 && !room.gameStarted) {
      startGameLoop(roomId);
      io.to(roomId).emit('gameStarted');
    }
  });
  
  // 离开房间
  socket.on('leaveRoom', ({ roomId }) => {
    leaveRoom(socket, roomId);
  });
  
  // 玩家输入
  socket.on('playerInput', (input) => {
    // 查找玩家所在的房间
    for (const roomId in rooms) {
      const room = rooms[roomId];
      if (room.players[socket.id]) {
        room.players[socket.id].input = input;
        break;
      }
    }
  });
  
  // 断开连接
  socket.on('disconnect', () => {
    console.log('用户已断开连接:', socket.id);
    
    // 查找玩家所在的房间并离开
    for (const roomId in rooms) {
      const room = rooms[roomId];
      if (room.players[socket.id]) {
        leaveRoom(socket, roomId);
        break;
      }
    }
  });
});

// 玩家离开房间
function leaveRoom(socket, roomId) {
  const room = rooms[roomId];
  if (!room) return;
  
  // 从房间中移除玩家
  if (room.players[socket.id]) {
    const playerName = room.players[socket.id].name;
    const playerColor = room.players[socket.id].color;
    const persistentId = room.players[socket.id].persistentId; // 获取持久化ID
    
    // 如果游戏已经开始，保存玩家的坦克状态而不是删除它
    if (room.gameStarted) {
      for (const tankId in room.gameState.tanks) {
        const tank = room.gameState.tanks[tankId];
        if (tank.playerId === socket.id) {
          // 标记坦克为断线状态，但保留其状态
          tank.disconnected = true;
          // 保存断线时间，用于可能的超时清理
          tank.disconnectTime = Date.now();
          // 保存玩家的坦克ID，用于重连时恢复
          room.players[socket.id].tankId = tankId;
          break;
        }
      }
    }
    
    // 保存玩家信息用于可能的重连
    if (!room.disconnectedPlayers) {
      room.disconnectedPlayers = {};
    }
    
    // 保存玩家的完整信息，包括坦克的所有状态
    const tankId = room.players[socket.id].tankId;
    let tankState = null;
    
    // 如果游戏已开始且玩家有坦克，保存完整的坦克状态
    if (room.gameStarted && tankId && room.gameState.tanks[tankId]) {
      tankState = { ...room.gameState.tanks[tankId] };
    }
    
    room.disconnectedPlayers[socket.id] = {
      id: socket.id,
      name: playerName,
      color: playerColor,
      tankId: tankId,
      tankState: tankState,
      disconnectTime: Date.now(),
      persistentId: persistentId // 保存持久化ID，用于重连时识别玩家
    };
    
    // 从房间中移除玩家
    delete room.players[socket.id];
    room.playerCount--;
    
    // 通知房间内所有玩家有玩家离开
    io.to(roomId).emit('playerLeft', {
      playerId: socket.id,
      playerName,
      playerCount: room.playerCount
    });
    
    // 如果房间内没有活跃玩家，立即删除房间
    if (room.playerCount <= 0) {
      // 清理逻辑更新定时器
      if (room.logicInterval) {
        clearInterval(room.logicInterval);
      }
      // 清理网络广播定时器
      if (room.networkInterval) {
        clearInterval(room.networkInterval);
      }
      delete rooms[roomId];
      console.log(`房间 ${roomId} 已删除`);
    }
    // 不再在这里判断游戏结束，只有当所有敌方坦克被摧毁时才判定游戏结束
    // 断线的玩家坦克仍然存在于游戏中，不应该立即宣布其他玩家获胜
  }
}

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器已启动，监听端口 ${PORT}`);
});